package com.mk.cloud.pt.controller.platform;

import act.Act;
import act.apidoc.Description;
import act.controller.Controller;
import act.inject.DefaultValue;
import com.alibaba.fastjson.JSON;
import com.mk.cloud.common.domain.*;
import com.mk.cloud.common.enums.ErrorCode;
import com.mk.cloud.common.enums.GlobalValues;
import com.mk.cloud.common.exception.UserException;
import com.mk.cloud.common.interceptor.ITransacte;
import com.mk.cloud.common.interceptor.cookie.CookieService;
import com.mk.cloud.common.interceptor.cookie.ICLogin;
import com.mk.cloud.common.util.DateUtils;
import com.mk.cloud.common.util.ResUtils;
import com.mk.cloud.common.util.S2;
import com.mk.cloud.common.util.pay.PayUtils;
import com.mk.cloud.pt.service.app.PCompanyService;
import com.mk.cloud.pt.service.app.RewardService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.annotation.PostAction;
import org.osgl.mvc.annotation.With;
import org.osgl.util.S;

import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller("applycash")
public class FlApplyCashController extends CookieService{

    @Inject
    private FlApplyCash.Mapper flApplyCashMapper;
    @Inject
    private FlCashFlow.Mapper flCashFlowMapper;
    @Inject
    private FlApplyCashHistory.Mapper flApplyCashHistoryMapper;
    @Inject
    private PUser.Mapper pUserMapper;
    @Inject
    private PCompanyService companyService;
    @Inject
    private RewardService rewardService;


    @Description("提现申请分页列表")
    @With(ICLogin.class)
    @GetAction("pageList.json")
    public PageQuery<FlApplyCash> pCompanyList(
            @Description("筛选条件-提现人名称") String realname,
            @Description("筛选条件-提现申请状态") String awfstate,
            @Description("当前第几页") @NotNull Integer currentPage,
            @Description("每页多少条") @DefaultValue("15") Integer pageSize

    ) {
        PageQuery<FlApplyCash> query = new PageQuery<>();
        query.setPageSize(pageSize);
        query.setPageNumber(currentPage);
        Map<String, Object> map = new HashMap<>();
        map.put("realname", realname);
        map.put("awfstate", awfstate);
        map.put("coid", me.getCoid());
        query.setParas(map);
        flApplyCashMapper.getSQLManager().pageQuery("flApplyCash.select_apply_cash_page_list", FlApplyCash.class, query);
        return query;
    }


    @PostAction("audit.json")
    @Description("审核提现申请")
    @With({ITransacte.class,ICLogin.class})
    public String auditApplyCash( String acid,
                                  String awfstate,
                                  String reason){
        FlApplyCash proApplyCash = flApplyCashMapper.single(acid);
        System.out.println(JSON.toJSONString(proApplyCash));
        if(!S.eq(proApplyCash.getAwfstate(),GlobalValues.AWF_STATE_0.value())){
            throw new UserException("该申请已经审核过,不能重复审核");
        }
        FlApplyCash applyCash = new FlApplyCash();
        applyCash.setAcid(acid);
        applyCash.setAwfstate(awfstate);
        applyCash.setReason(reason);
        applyCash.setAwfdate(DateUtils.getTimeNow());
        applyCash.setAuid(me.getUserid());
        applyCash.setAuname(me.getRealname());
        flApplyCashMapper.updateTemplateById(applyCash);
        if(S.eq(GlobalValues.AWF_STATE_2.value(),awfstate)){
            //如果审核驳回,则减少锁定金额
            pUserMapper.lockAmountByFuserid(proApplyCash.getFuserid(),proApplyCash.getWdamount().multiply(new BigDecimal("-1")));
            //TODO 审核驳回减少锁定金额
            //TODO 增加钱包提现驳回展示
            PUser pUser = pUserMapper.single(proApplyCash.getFuserid());
            rewardService.addFlow(pUser,pUser.getFuserid(),GlobalValues.FLOW_TYPE_0.value(),proApplyCash.getWdamount(),pUser.getWalletamount().subtract(pUser.getLockamount()),GlobalValues.SOURCETYPE_3.value(),reason);
        }
        addApplyCashHistory(applyCash,proApplyCash.getAwfstate(),"审核提现申请");
        return ResUtils.OK();
    }

    /**
     * 添加历史记录
     */
    @With({ITransacte.class})
    private void addApplyCashHistory(FlApplyCash applyCash,String beforstatus,String description){
        FlApplyCashHistory history = new FlApplyCashHistory();
        history.setAchid(S2.UUID());
        history.setCoid(me.getCoid());
        history.setBuilddate(DateUtils.getTimeNow());
        history.setBeforstatus(beforstatus);
        history.setAfterstatus(applyCash.getAwfstate());
        history.setPaytype(GlobalValues.PAY_TYPE_2.value());

        history.setAcid(applyCash.getAcid());
        history.setDescription(description);
        flApplyCashHistoryMapper.insert(history);

    }

    /**
     * 校验图形验证码
     * @param code
     */
    private void checkImgCode(@Description("图形验证码") String code,
                              @Description("时间戳") String timestamp) {
        //region 图形验证码开始验证
        UserException.throwIf(StringUtils.isBlank(code), ErrorCode.E201014);
        String cachedCodeImg = Act.cache().get(timestamp);
        UserException.throwIf(!StringUtils.equalsIgnoreCase(cachedCodeImg,code),ErrorCode.E201009);
        //endregion
    }

    /**
     * 提现申请付款
     * @param acid
     */
    @PostAction("transfer.json")
    @With({ICLogin.class,ITransacte.class})
    public String transfer(String acid){

        FlApplyCash applyCash = flApplyCashMapper.single(acid);
        //判断是否符合提现条件
        if(applyCash == null){
            throw new UserException("该提现申请不存在");
        }else if(S.eq(applyCash.getAwfstate(),GlobalValues.AWF_STATE_0.value())||S.eq(applyCash.getAwfstate(),GlobalValues.AWF_STATE_2.value())){
            throw new UserException("该申请未审核通过,不能转账");
        }else if(S.eq(applyCash.getAwfstate(),GlobalValues.AWF_STATE_3.value())
                ||S.eq(applyCash.getAwfstate(),GlobalValues.AWF_STATE_4.value())
                ||S.eq(applyCash.getAwfstate(),GlobalValues.AWF_STATE_5.value())
                ){
            throw new UserException("该申请已经提现完成,不能重复操作");
        }else if(S.eq(applyCash.getAwfstate(),GlobalValues.AWF_STATE_1.value())){//审核通过,可以提现
            //region 提现处理开始
            PCoconfig coconfig = companyService.getCompanyByCoid(applyCash.getCoid()).getPCoconfig();
            //TODO 支付宝转账是用到
            if(coconfig==null||S.isBlank(coconfig.getAliappid())){
                throw new UserException("支出账户未配置,请先配置支出的支付宝账户信息");
            }
            PayUtils payUtils = PayUtils.payFactory("2",coconfig);
            Map<String,Object> map = new HashMap<>();
            map.put("payid",acid);
            map.put("realname",applyCash.getAliname());
            map.put("payeetype","ALIPAY_LOGONID ");
            map.put("payeeaccount",applyCash.getAliaccount());
            BigDecimal amount = applyCash.getWdamount();
            if(applyCash.getWdfees()!=null){
                amount = applyCash.getWdamount().subtract(applyCash.getWdfees());
            }
            map.put("amount",amount);
            map.put("remark","合伙人提现");
            String flag = payUtils.transfer(map);

            FlCashFlow cashFlow = new FlCashFlow();
            cashFlow.setCfid(S2.UUID());
            cashFlow.setFuserid(applyCash.getFuserid());
            cashFlow.setPayorderno(acid);
            cashFlow.setWdamount(applyCash.getWdamount());
            cashFlow.setWdfees(applyCash.getWdfees());
            cashFlow.setRefamount(cashFlow.getRefamount());
            cashFlow.setAwfdate(DateUtils.getTimeNow());
            cashFlow.setUserid(me.getUserid());
            cashFlow.setUsername(me.getRealname());
            cashFlow.setCoid(applyCash.getCoid());

            FlApplyCash flApplyCash = new FlApplyCash();
            flApplyCash.setAcid(acid);
            String prestate = applyCash.getAwfstate();
            if(S.eq(flag,"true")){//提现成功
                cashFlow.setFlowstate(GlobalValues.FLOW_STATE_0.value());
                flApplyCash.setAwfstate(GlobalValues.AWF_STATE_3.value());
                applyCash.setAwfstate(GlobalValues.AWF_STATE_3.value());
                addApplyCashHistory(applyCash,prestate,"提现成功");
            }else{//提现失败
                cashFlow.setFlowstate(GlobalValues.FLOW_STATE_1.value());
                cashFlow.setRemark("支付宝打款失败，失败原因:" + flag);

                flApplyCash.setAwfstate(GlobalValues.AWF_STATE_4.value());
                applyCash.setAwfstate(GlobalValues.AWF_STATE_3.value());
                addApplyCashHistory(applyCash,prestate,"提现失败");
                throw new UserException(cashFlow.getRemark());
            }
            //增加提现流水
            flCashFlowMapper.insert(cashFlow);
            //更新状态
            flApplyCashMapper.updateTemplateById(flApplyCash);

            //endregion 提现处理结束
            return "0";
        }
        return "";
    }
}
